import datetime
from django.utils import timezone
from django.db.models import Sum
from django.contrib.contenttypes.models import ContentType
from .models import ReadNum, ReadDetail

def increase_read_num(request, obj):
    ct = ContentType.objects.get_for_model(obj)
    cookie_key = "{}_{}_readnum".format(ct.model, obj.pk)
    if not request.COOKIES.get(cookie_key):
        # 总阅读量+1
        read_record, created = ReadNum.objects.get_or_create(content_type=ct, object_id=obj.pk)
        read_record.read_num += 1
        read_record.save()

        # 当天阅读量+1
        date = timezone.now().date()
        read_detail, created = ReadDetail.objects.get_or_create(content_type=ct, object_id=obj.pk, date=date)
        read_detail.read_num += 1
        read_detail.save()

    return cookie_key

def last_seven_days_read_detail(content_type):
    today_date = timezone.now().date() 
    dates = []
    read_sums = []
    for i in range(7, 0, -1):
        date = today_date-datetime.timedelta(days=i)
        dates.append(date.strftime("%m/%d"))
        result = ReadDetail.objects.filter(content_type=content_type, date=date).aggregate(read_sum=Sum('read_num'))
        read_sums.append(result['read_sum'] or 0)
    return dates, read_sums

def get_one_day_hot_detail(date):
    read_details = ReadDetail.objects.filter(date=date).order_by('-read_num')
    return read_details[:7]
